<?php

class SiteController extends Controller
{
	
	
	
	public function __construct($id)
	{
		
		parent::__construct($id);
		
		$this->layout = '//layouts/site';		
		
	}
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex()
	{
		// renders the view file 'protected/views/site/index.php'
		// using the default layout 'protected/views/layouts/main.php'
		
		//$this->setMetaInfo();

		$this->render('index',array(
			
		));
	}
    
    public function actionGetMenus($id)
    {
        $links = '';
        $result = Category::model()->findAll(array(
            'condition'=>'cate_type = :type AND cate_pid != 0',
            'order'=>'cate_order DESC',
            'params'=>array(
                ':type'=>$id
            )
        ));
        
        foreach($result as $item)
        {
            $links .= CHtml::link($item->cate_name, array('/labs/demo','id'=>$item->cate_id));
        }
        
        echo $links;
        
        
    }
	
	public function actionCacheTest()
	{
		$cache = Yii::app()->fileCache;
		$time = $cache->get('list');
		if(false == $time)
		{
			$result = Category::model()->findAll();
			$time = $cache->set('list',$result,3);
		}	
		var_dump($time);
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}

	/**
	 * Displays the contact page
	 */
	public function actionContact()
	{
		
		$this->meta['Description'] = '如果有需要，可以填写下表与我取得联系';
		$this->meta['KeyWords'] = '联系我';
		
		$this->setMetaInfo();
		
		require 'Zend/Mail/Protocol/Smtp/Auth/Login.php';
        require_once 'Zend/Mail.php';
        require_once 'Zend/Mail/Transport/Smtp.php';

//      $config = array(
//			'auth' => 'login',
//          'username' => 'zclandxy',
//          'password' => 'zclandxy5424346',
//          'ssl' => 'SSL'
//         );
		$config = array(
			'auth' => 'login',
			'username' => 'admin@yuekegu.com',
			'password' => 'zclandxy5424346'
		);

        $transport = new Zend_Mail_Transport_Smtp('smtp.yuekegu.com', $config);
        
		
		$model=new ContactForm;
		if(isset($_POST['ContactForm']))
		{
			$model->attributes=$_POST['ContactForm'];
			
			$mail = new Email();
			$mail->mail_body = $model->body;
			$mail->mail_email = $model->email;
			$mail->mail_name = $model->name;
			$mail->mail_subject = $model->subject;
			$mail->mail_created = time();
			$mail->mail_ip = ip2long(Yii::app()->request->getUserHostAddress());
			
//			echo UtilTools::getClientIp();
//			
//			UtilTools::dump($_SERVER);
//			UtilTools::dump($mail->attributes);
//			
//			Yii::app()->end();
		
			if($model->validate() && $mail->save())
			{
//				$headers="From: {$model->email}\r\nReply-To: {$model->email}";
//				mail(Yii::app()->params['adminEmail'],$model->subject,$model->body,$headers);

//				if($mail->save())
//				{
					$mail = new Zend_Mail('UTF-8');
					
					$mail->setHeaderEncoding(Zend_Mime::ENCODING_BASE64);
					
			        $mail->setBodyHtml($model->email.'<br />'.$model->body);
			        $mail->setFrom('admin@yuekegu.com', $model->name);
//			        $mail->addTo(Yii::app()->params['mail'], Yii::app()->params['author']);
					$mail->addTo('dajjwwx@163.com', 'Receiver');
			        $mail->setSubject($model->subject);
			        $mail->send($transport);					
//				}	        
		        
				
				
				Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
				$this->refresh();
			}
		}
		$this->render('contact',array('model'=>$model));
	}

	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
//		$this->layout = '//layouts/blank';

//		die($_SERVER['HTTP_REFERER']);

		$this->meta['Description'] = '在此填写登录及注册信息';
		$this->meta['KeyWords'] = '登录/注册';
		
		$this->setMetaInfo();
		
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
		
	

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
				
// 				echo Yii::app()->request->urlReferrer;
//				$this->redirect($_SERVER['HTTP_REFERER']);
				//$this->redirect(Yii::app()->request->urlReferrer);

				if (isset($_GET['referer']))
					$this->redirect($_GET['referer']);
				else if($this->id == 'site' && $this->action->id == 'login')
					$this->redirect($this->createUrl('/blog'));
				else
					$this->redirect(Yii::app()->request->urlReferrer);
				

			}
				
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}
	
	public function actionLoginAjax()
	{
		$this->layout = '//layouts/blank';
		
		//		die($_SERVER['HTTP_REFERER']);

		
		$model=new LoginForm;
		
		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}	
		
		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];
			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login()){
				//				$this->redirect($_SERVER['HTTP_REFERER']);
				$this->redirect(Yii::app()->request->urlReferrer);
		
				//				if (isset($_GET['referer']))
					//					$this->redirect($_GET['referer']);
					//				else
						//					$this->redirect($this->createUrl('/admin'));
		
		
			}
		
		}
		// display the login form
		$this->render('login',array('model'=>$model));		
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}

	public function actionTest3()
	{
		//function getPerfectImage($src,$des,$width,$height,$border=1,$isMask=false,$masksrc='',$maskpos=4

		$src = './public/upload/Product/2011/08/24/5c0de63c9777c6fc43b91d64a6d11606.png';
		$des = './public/upload/Product/2011/08/24/5c0de63c9777c6fc43b91d64a6d11606_thumb.png';
		$width = 160;
		$height = 200;
		$border = 1;
		$isMask = false;
		$marsksrc = '';
		$maskpos = 4;
		
		$pathinfo = pathinfo($src);
		$ext = $pathinfo['extension'];
		$tmp = './upload/'.md5(time().rand(1, 1000)).'.'.$ext;
		
		$t = new ThumbHandler();
		$t->setSrcImg($src);		
		
		$t->setCutType(1);//指明为手工裁切
		$t->setImgDisplayQuality(90);
		$t->setDstImg($tmp);
		
		$w = $t->getSrcImgWidth();
		$h = $t->getSrcImgHeight();
		
		//宽度缩放比例
		$num_w = ($width/$w)*100;
		//如果以宽缩放为标题，则目标图片高度
		$tar_h = $h*$width/$w;
		
		//高度缩放比例
		$num_h = ($height/$h)*100;
		//如果以高缩放为标准，则目标图片宽度
		$tar_w = $w*$height/$h;
		
		if($num_w > $num_h && $tar_h>=$height)
		{
			$num = $num_w;
		}else if($num_w > $num_h && $tar_h < $height){
			$num = $num_h;
		}else if($num_w < $num_h && $tar_w >= $width){
			$num = $num_h;
		}else{
			$num = $num_w;
		}
		
//		$w = $t->getSrcImgWidth();
//		
//		$num = ceil(($width/$w)*100);

		$t->createImg($num);
//		$num = 250/$ss;
//		590*300
//		550*300	72		
		$t = new ThumbHandler();
		$t->setImgDisplayQuality(90);
		$t->setSrcImg($tmp);
		if($isMask){
			$t->setMaskImg($masksrc);
			$t->setMaskPosition($maskpos);
			$t->setMaskImgPct(30);			
		}	

		
		$t->setCutType(2);//指明为手工裁切
		$t->setSrcCutPosition(0, 0);// 源图起点坐标
		$t->setRectangleCut($width-8, $height-8);// 裁切尺寸
		$t->setImgDisplayQuality(90);
		$t->setDstImg($des);
		$t->setDstImgBorder(4,"#dddddd");
		$t->createImg($width,$height);
		
		unlink($tmp);
	}
	
	public function actionTest2()
	{
//		require 'Zend/Mail.php';
//		require 'Zend/Mail/Transport/Smtp.php';
//		require 'Zend/Mail/Protocol/Smtp/Auth/Login.php';
//		require 'Zend/Mail/Protocol/Exception.php';
//		
//		
//		$config = array(
//			'auth' => 'login', 
//			'username' => 'dajjwwx@163.com',
//			'password' => 'dajjwwxdajjwwx',
//		);
//		$transport = new Zend_Mail_Transport_Smtp('smpt.163.com',$config);
//		
//		Zend_Mail::setDefaultFrom('dajjwwx@163.com','Dajjwwx');
//		Zend_Mail::setDefaultReplyTo('zclandxy@gmail.com', 'Dajjwwx2');
//		
//		for ($i = 0; $i < 3; $i++)
//		{
//			$mail = new Zend_Mail();	
//			$mail->setBodyText("This is the text of the mail <$i>");
//			$mail->setFrom("zclandxy@gmail.com","Sender");
//			$mail->addTo("dajjwwx@163.com","Some Recipient");
//			$mail->setSubject("Test Subject");
//			$mail->send($transport);				
//		}
//		
//		Zend_Mail::clearDefaultFrom();
//		Zend_Mail::clearDefaultReplyTo();
		require 'Zend/Mail/Protocol/Smtp/Auth/Login.php';
        require_once 'Zend/Mail.php';
        require_once 'Zend/Mail/Transport/Smtp.php';

//      $config = array(
//			'auth' => 'login',
//          'username' => 'zclandxy',
//          'password' => 'zclandxy5424346',
//          'ssl' => 'SSL'
//         );
		$config = array(
			'auth' => 'login',
			'username' => 'admin@yuekegu.com',
			'password' => 'zclandxy5424346'
		);

        $transport = new Zend_Mail_Transport_Smtp('smtp.yuekegu.com', $config);

        $mail = new Zend_Mail();
        $mail->setBodyText('This is the text of the mail.');
        $mail->setFrom('admin@yuekegu.com', 'Some Sender');
        $mail->addTo('dajjwwx@163.com', 'Some Recipient');
        $mail->setSubject('TestSubject');
        $mail->send($transport);
	}
	
	public function actionTest5()
	{
		$circle = $square = array();
		
		for($i = 1; $i < 100; $i++)
		{
			$circle[] = $square[] = $i;
		}
		
		foreach ($square as $ck=>$cv)
		{
			foreach ($circle as $sk => $sv) {
				$this->test($circle[$ck], $square[$sk]);
			}
		}
		
		$this->test(24);
	}
	
	public function actionTest()
	{
		if (isset($_POST))
		{
			UtilTools::dump($_POST);
		}
		$this->render('test');
	}    

}